package com.hikeen.launcherx;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hikeen.launcherx.adapter.AllAdapter;
import com.hikeen.launcherx.bean.AppInfos;
import com.hikeen.launcherx.bean.AppInfoss;
import com.hikeen.launcherx.floatwindow.EventMessage;
import com.hikeen.launcherx.ui.MainActivity3;
import com.hikeen.launcherx.utils.AppUtils;
import com.hikeen.launcherx.utils.FileImageUtils;
import com.hikeen.launcherx.utils.GsonUtils;
import com.hikeen.launcherx.utils.SPUtils;
import com.hjq.toast.ToastUtils;
import com.hikeen.launcherx.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ThreeFramgent extends Fragment {
    private TextView text;
    private RecyclerView app_recycle;
    private ArrayList<AppInfos> allApp;
    private AllAdapter allMyAdapater;
    private GridLayoutManager linearLayoutManager;
    private String savePath="TVjieping";
    private DisplayMetrics mDisplayMetrics;
    private Bitmap bitmap;
    private LocalBroadcastManager broadcastManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_three_layout, container, false);
        initView(view);


        return view;
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        // Do something
        if (event.getType()==11){
            if (event.getMessage().equals("refreshlist")){
                ToastUtils.show("refreshlist");
                chushihua(event.getMessage2());
            }
        }
    }





    private void initView(View view) {
        text = (TextView) view.findViewById(R.id.text);
        app_recycle = view.findViewById(R.id.app_recycle);

        allApp = new ArrayList<AppInfos>();
        allApp = AppUtils.getAppInfo(getContext());
        allMyAdapater = new AllAdapter(getContext(), allApp);

        linearLayoutManager = new GridLayoutManager(getContext(),6);
        app_recycle.setLayoutManager(linearLayoutManager);

        app_recycle.setAdapter(allMyAdapater);

        //点击跳转apk
        allMyAdapater.setOnItemClickListener(new AllAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                MainActivity3.isShowOne = true;
                //这里通过包名来跳转
                Intent mIntent = new Intent();
                PackageManager packageManager = getActivity().getPackageManager();
                AppInfos appInfo = allApp.get(position);




                mIntent = packageManager.getLaunchIntentForPackage(appInfo.getPackageName());
                if (mIntent != null) {
                    startActivity(mIntent);
                }
                //延时三秒 执行截屏操作

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            Thread.sleep(2000); // 休眠1秒
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 延时执行的代码
                         */

//                        Bitmap bitmap = AppUtils.GetandSaveCurrentImage(getActivity());
//                       screenShotByReflect();
//                        if (bitmap==null){
//                            ToastUtils.show("截屏失败");
//                        }else {
//                            ToastUtils.show("截屏成功");
//                        }


                        String s = FileImageUtils.savefilePath(getContext(), appInfo.getAppName());


                        File filePic = new File(s);

                        filePic.getParentFile().mkdirs();
                        screenShotByShell(s);



                    }
                }).start();



                //保存当前打开的APP  到第一条


                String savelist = SPUtils.getString("savelist", "");
                List<AppInfoss> saveL = new ArrayList<>();
                if (TextUtils.isEmpty(savelist)){
                    AppInfoss appInfoss = new AppInfoss();
                    appInfoss.setAppName(allApp.get(position).getAppName());
                    appInfoss.setPackageName(allApp.get(position).getPackageName());
                    saveL.add(appInfoss);

                }else {
                    List<AppInfoss> appInfosses = GsonUtils.getPersons(savelist, AppInfoss.class);
                    int index = -1 ;
                    for (int i = 0; i < appInfosses.size(); i++) {
                        if (allApp.get(position).getAppName().equals(appInfosses.get(i).getAppName()) &&
                                allApp.get(position).getPackageName().equals(appInfosses.get(i).getPackageName()) ){
                            index = i;
                        }
                    }
                    if (index>=0){
                        appInfosses.remove(index);
                    }

                    AppInfoss appInfoss = new AppInfoss();
                    appInfoss.setAppName(allApp.get(position).getAppName());
                    appInfoss.setPackageName(allApp.get(position).getPackageName());

                    if (appInfosses.size()>7){
                        appInfosses.remove(appInfosses.size()-1);
                        appInfosses.add(0,appInfoss);
                    }else {
                        appInfosses.add(0,appInfoss);
                    }
                    saveL.addAll(appInfosses);

                }

                String s = new Gson().toJson(saveL);

                Log.e("appinfo", "onClick: "+s);

                SPUtils.putString("savelist",s);


            }
        });
        //长按卸载apk，但是我这里没有做刷新的操作，需要注意一下
        allMyAdapater.setOnItemLongClickListener(new AllAdapter.OnItemLongClickListener() {
            @Override
            public void onClick(int position) {
                AppInfos appInfo = allApp.get(position);
                uninstall(appInfo.getPackageName());
            }
        });
    }

    public void chushihua(String message2) {
//        ToastUtils.show("chushihua");
        allApp = new ArrayList<AppInfos>();
        allApp = AppUtils.getAppInfo(getContext());

     if (!TextUtils.isEmpty(message2)){
         int index = -1 ;
         for (int i = 0; i < allApp.size(); i++) {
             if (message2.equals(allApp.get(i).getPackageName()) ){
                 index = i;
             }
         }
         if (index>=0) {
             allApp.remove(index);
         }
     }
        allMyAdapater = new AllAdapter(getContext(), allApp);
        Log.e("初始化ss", "chushihua: "+allApp.size() );

        app_recycle.setAdapter(allMyAdapater);

        //点击跳转apk
        allMyAdapater.setOnItemClickListener(new AllAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                MainActivity3.isShowOne = true;
                //这里通过包名来跳转
                Intent mIntent = new Intent();
                PackageManager packageManager = getActivity().getPackageManager();
                AppInfos appInfo = allApp.get(position);

                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mIntent = packageManager.getLaunchIntentForPackage(appInfo.getPackageName());
                if (mIntent != null) {
                    startActivity(mIntent);
                }
                //延时三秒 执行截屏操作

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            Thread.sleep(2000); // 休眠1秒
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }



                        String s = FileImageUtils.savefilePath(getContext(), appInfo.getAppName());


                        File filePic = new File(s);

                        filePic.getParentFile().mkdirs();
                        screenShotByShell(s);


                    }
                }).start();



                //保存当前打开的APP  到第一条


                String savelist = SPUtils.getString("savelist", "");
                List<AppInfoss> saveL = new ArrayList<>();
                if (TextUtils.isEmpty(savelist)){
                    AppInfoss appInfoss = new AppInfoss();
                    appInfoss.setAppName(allApp.get(position).getAppName());
                    appInfoss.setPackageName(allApp.get(position).getPackageName());
                    saveL.add(appInfoss);

                }else {
                    List<AppInfoss> appInfosses = GsonUtils.getPersons(savelist, AppInfoss.class);
                    int index = -1 ;
                    for (int i = 0; i < appInfosses.size(); i++) {
                        if (allApp.get(position).getAppName().equals(appInfosses.get(i).getAppName()) &&
                                allApp.get(position).getPackageName().equals(appInfosses.get(i).getPackageName()) ){
                            index = i;
                        }
                    }
                    if (index>=0){
                        appInfosses.remove(index);
                    }

                    AppInfoss appInfoss = new AppInfoss();
                    appInfoss.setAppName(allApp.get(position).getAppName());
                    appInfoss.setPackageName(allApp.get(position).getPackageName());

                    if (appInfosses.size()>7){
                        appInfosses.remove(appInfosses.size()-1);
                        appInfosses.add(0,appInfoss);
                    }else {
                        appInfosses.add(0,appInfoss);
                    }
                    saveL.addAll(appInfosses);

                }

                String s = new Gson().toJson(saveL);

                Log.e("appinfo", "onClick: "+s);

                SPUtils.putString("savelist",s);


            }
        });
        //长按卸载apk，但是我这里没有做刷新的操作，需要注意一下
        allMyAdapater.setOnItemLongClickListener(new AllAdapter.OnItemLongClickListener() {
            @Override
            public void onClick(int position) {
                AppInfos appInfo = allApp.get(position);
                uninstall(appInfo.getPackageName());
            }
        });
    }






    public boolean uninstall(String packageName) {
        boolean b = checkApplication(packageName);
        if (b) {
            Uri packageURI = Uri.parse("package:".concat(packageName));
            Intent intent = new Intent(Intent.ACTION_DELETE);
            intent.setData(packageURI);
            this.startActivity(intent);
            return true;
        }
        return false;
    }

    private boolean checkApplication(String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        return true;
    }





    //使用反射调用截屏
    private void screenShotByReflect(){
        mDisplayMetrics = new DisplayMetrics();
        float[] dims = { mDisplayMetrics.widthPixels,
                mDisplayMetrics.heightPixels };
        try {
            Class<?> demo = Class.forName("android.view.SurfaceControl");
            Method method = demo.getDeclaredMethod("screenshot", int.class,int.class);
            bitmap = (Bitmap) method.invoke(null,(int) dims[0],(int) dims[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




//    三、使用screencap的adb命令
//
//    命令行是这样的：adb shell screencap -p file_path
//
//    在代码中执行，就不用adb shell，直接screencap -p file_path，调用Runtime的进程来执行：

    public static void screenShotByShell(String filePath){
        String shotCmd = "screencap -p " + filePath + " \n";
        try {
            Runtime.getRuntime().exec(shotCmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if(!EventBus.getDefault().isRegistered(this)){//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
